<?php

namespace App\Http\Controllers;

use App\Models\Details;
use App\Models\Orders;
use App\Models\System;
use Carbon\Carbon;
use EasyWeChat\Factory;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class WechatController extends Controller
{
    /**
     * 支付回调
     */
    public function payCallback(){

        $config = [
            // 必要配置
            'app_id' => env('WECHAT_OFFICIAL_ACCOUNT_APPID'),

            'mch_id' => '1607422347',

            'key' => env('WECHAT_APP_PAY_SECRET'),   // API 密钥

            'notify_url' => env('APP_URL') . '/wechat/payCallback',     // 你也可以在下单时单独设置来想覆盖它
        ];

        $app = Factory::payment($config);

        $response = $app->handlePaidNotify(function($message, $fail){

            //查找订单
            $order = Orders::where('order_sn' , $message['out_trade_no'])->first();

            if (empty($order)) { // 如果订单不存在
                return $fail('订单没找到，请稍后再通知我');
            }

            //////// <-在这里调用微信的【订单查询】接口查一下该笔订单的情况，确认是已经支付 /////////

            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                // 用户是否支付成功
                if (Arr::get($message , 'result_code') === 'SUCCESS') {

                    $order->status = 2;

                    $order->transaction_sn = $message['transaction_id'];

                    $order->bank_type = $message['bank_type'];

                    $order->pay_at = date('Y-m-d H:i:s' , time());

                    // 用户支付失败
                } elseif (Arr::get($message , 'result_code') === 'FAIL') {
                    $order->status = 7;
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }

            if($order->save()){ // 保存订单
                $reward = json_decode($message['attach'] , true);

                if(!empty($reward['user_id']) && !empty($reward['parent_user_id'])){
                    $systemReward = System::where('id' , 999)->value('reward');

                    $money = round(round($message['total_fee']/100,2)* $systemReward / 100 , 2);

                    Details::create([
                        'order_sn' => $message['out_trade_no'],
                        'user_id' => $reward['parent_user_id'], //下单用户的所属上级用户id
                        'invitee_user_id' => $reward['user_id'], //下单用户ID
                        'money' => $money,
                        'reward' => $systemReward,
                        'expect_at' =>Carbon::now()->addDays(10),
                        'status' => 1,
                    ]);
                }
            }
            return true; //处理完成
        });

        $response->send(); // return $response;
    }

    /**
     * 退款回调
     */
//    public function refundCallback(){
//
//        $app = Factory::payment(config('wechat.payment.default'));
//
//        $response = $app->handlePaidNotify(function($message, $fail){
//
//            file_put_contents('haojie.php' , json_encode($message , JSON_UNESCAPED_UNICODE));
//            dd(1);
//
//            //查找订单
//            $order = Orders::where('order_sn' , $message['out_trade_no'])->first();
//
//            if (empty($order)) { // 如果订单不存在
//                return $fail('订单没找到，请稍后再通知我');
//            }
//
//
//            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
//                // 用户是否支付成功
//                if (Arr::get($message , 'result_code') === 'SUCCESS') {
//
//                } elseif (Arr::get($message , 'result_code') === 'FAIL') {
//                    $order->status = 7;
//                }
//            } else {
//                return $fail('通信失败，请稍后再通知我');
//            }
//
//            if($order->save()){ // 保存订单
//
//            }
//            return true; //处理完成
//        });
//
//        $response->send(); // return $response;
//    }



    /**
     * 设置自定义菜单
     */
    public function wechatMenu(){

        $app = Factory::officialAccount(config('wechat.official_account.default'));

        $list = $app->menu->list();

        $buttons = [
            [
                "type" => "view",
                "name" => "兼职中心",
                "url"  => "http://shop.srswkj.cn"
            ],
            [
                "type" => "view",
                "name" => "代理中心",
                "url"  => "http://cosmetics.ikunc.com/login"
            ],
            [
                "name"       => "官方网站",
                "sub_button" => [
                    [
                        "type" => "miniprogram",
                        "name" => "素材库",
                        "url"  => "http://mp.weixin.qq.com",
                        "appid" => "wx9626a2bab392aae4",
                        "pagepath" => "pages/index/index",

                    ],
                    [
                        "type" => "view",
                        "name" => "官方网站",
                        "url"  => "http://srswkj.cn/"
                    ],


                ],
            ],
        ];
        $status = $app->menu->create($buttons);

        dd($status);
    }
}
